﻿Imports System.Collections.Generic
Imports System.Net
Imports System.ComponentModel
Imports System.IO
Imports System.Windows.Forms
Imports System.Timers

Public Enum downloadResult

    Exception = 1
    Success = 0
    None = -1
    Downloading = -2
End Enum

Module modDownload
    Dim publicResult As downloadResult

    Private _timer As System.Windows.Forms.Timer
    Private _seconds As Integer = 0
    Private _downloadStatus As downloadResult = downloadResult.None
    Private _abort As Boolean = False

    Public Function Download_File(ByVal fileURL As String, Optional ByVal fileDirectory As String = Nothing,
                                  Optional ByVal fileName As String = Nothing, Optional fileOverwrite As Boolean = True) _
        As downloadResult

        Dim _remoteURL As String
        Dim _fileName As String
        Dim _localPath As String

        If (fileDirectory Is Nothing) Then

            fileDirectory = AppDomain.CurrentDomain.BaseDirectory

        End If

tryDownload:

        publicResult = downloadResult.None

        _remoteURL = fileURL

        Using net As New WebClient

            AddHandler net.DownloadProgressChanged, AddressOf Download_Progress
            AddHandler net.DownloadFileCompleted, AddressOf Download_Complete

            _fileName = Path.GetFileName(_remoteURL)

            If (fileName IsNot Nothing) Then

                _fileName = fileName

            End If

            _fileName = _fileName.Replace("%20", Chr(32))

            _localPath = Path.Combine(fileDirectory, _fileName)

            If File.Exists(_localPath) Then

                File.Delete(_localPath)

            End If

            publicResult = downloadResult.None

            Timer_Start()

            net.DownloadFileAsync(New Uri(_remoteURL), _localPath)

            While (publicResult <> downloadResult.Success) And (_abort = False)

                Application.DoEvents()

            End While

            If _abort = True Then
                Dim iMsgbox = MsgBox("Error downloading """ & Path.GetFileName(_remoteURL) & """. Would you like to try again?", vbYesNo + vbExclamation, "Demonbuddy Modification Assistant")

                If iMsgbox = vbYes Then

                    GoTo TryDownload

                End If
            End If

            Return publicResult

        End Using

    End Function
    Public Sub Timer_Start()

        _timer = New System.Windows.Forms.Timer
        AddHandler _timer.Tick, AddressOf Timer_Tick
        _timer.Interval = 1000
        _downloadStatus = downloadResult.None
        _abort = False
        _seconds = 0

    End Sub

    Public Sub Timer_Tick()

        _seconds = _seconds + 1

        If publicResult <> _downloadStatus Then

            _seconds = 0

        End If

        If _seconds = 5 Then

            _abort = True

        End If

    End Sub

    Public Sub Download_List(ByVal fileURL As List(Of String), Optional ByVal fileDirectory As String = Nothing,
                             Optional ByVal fileNames As List(Of String) = Nothing,
                             Optional fileOverwrite As Boolean = True,
                             Optional ByRef results As List(Of downloadResult) = Nothing)

        Dim _remoteURL As String
        Dim _fileName As String
        Dim _localPath As String
        Dim _result As downloadResult

        _result = downloadResult.None

        If (fileDirectory Is Nothing) Then

            fileDirectory = AppDomain.CurrentDomain.BaseDirectory

        End If

        For i As Integer = 0 To (fileURL.Count - 1)

            _remoteURL = fileURL.Item(i)

            _fileName = Path.GetFileName(_remoteURL)

            If (fileNames IsNot Nothing) Then

                _fileName = fileNames(i)

            End If

            _localPath = Path.Combine(fileDirectory, _fileName)

            If File.Exists(_localPath) Then

                File.Delete(_localPath)

            End If

            _result = Download_File(_remoteURL, fileDirectory, _fileName.Replace("%20", String.Empty))

            If (results IsNot Nothing) Then

                results.Add(_result)

            End If

        Next
    End Sub

    Private Sub Download_Progress(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)

        publicResult = downloadResult.Downloading

    End Sub

    Private Sub Download_Complete(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)

        If (e.Error Is Nothing) Then

            publicResult = downloadResult.Success

        Else

            publicResult = downloadResult.Exception

        End If
    End Sub
End Module